package com.semidata.trp.decision.business;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.semidata.rtd.core.log.Logger;
import com.semidata.rtd.core.service.ServiceManager;
import com.semidata.rtd.engine.dynamic.DynamicClassLoader;
import com.semidata.rtd.engine.dynamic.DynamicCompiler;
import com.semidata.trp.decision.bid.CompileEvent;
import com.semidata.trp.decision.bid.CompileService;
import com.semidata.trp.message.business.Business;
import com.semidata.trp.message.business.Business.Strategy.ResourcePrice;

public class BusinessData {

	private Map<Integer, Position> positions = new HashMap<>();
	private Map<Integer, Class<?>> algos = new HashMap<>();

	public BusinessData() {
	}

	public BusinessData(Business.BusinessData data) {

		Map<Integer, Resource> resources = new HashMap<>();
		Map<Integer, Material> materials = new HashMap<>();

		for (Business.Position item : data.getPositionsList()) {
			Position position = new Position(item);
			positions.put(position.getId(), position);
		}

		for (Business.Material item : data.getMaterialsList()) {
			Material material = new Material(item);
			materials.put(material.getId(), material);
		}

		for (Business.Resource item : data.getResourcesList()) {
			Resource resource = new Resource(item);
			resources.put(resource.getId(), resource);
			int positionId = item.getPositionId();
			Position position = positions.get(positionId);
			if (position == null) {
				throw new RuntimeException("can not find position, id = "
						+ positionId);
			}
			position.addResource(resource);
			resource.setPosition(position);
			resource.setAllowShared(item.getAllowShared());
			Set<String> areas = new HashSet<>();
			areas.addAll(item.getAreasList());
			resource.setAreas(areas);
			Set<Integer> hours = new HashSet<>();
			hours.addAll(item.getHoursList());
			resource.setHours(hours);
		}

		for (Business.Strategy item : data.getStrategiesList()) {
			for (ResourcePrice obj : item.getResourcePricesList()) {
				Resource resource = resources.get(obj.getResourceId());
				if (resource == null)
					continue;
				Strategy strategy = new Strategy(item, resource,
						obj.getPrice(), materials);
				resource.addStrategy(strategy);
			}
		}

		for (Resource resource : resources.values()) {
			resource.sort();
		}

		CompileService compileService = ServiceManager.getService(CompileService.class); 
		for (Business.Algorithm algo : data.getAlgorithmsList()) {
			int id = algo.getId();
			String code = algo.getCode();
			CompileEvent event = new CompileEvent(id,code);
			compileService.send(event);
		}
	}

	public Position getPosition(int id) {
		return positions.get(id);
	}
	
	public Map<Integer,Class<?>> getAlgos() {
		return this.algos;
	}

	public String toString() {
		StringBuffer sb = new StringBuffer();
		for (Position position : positions.values()) {
			sb.append(position.toString());
			sb.append('\n');
		}
		return sb.toString();
	}
}
